package com.lijiajia.cloud.common.core.jackson.databind;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.lijiajia.cloud.common.core.Constants;
import com.lijiajia.cloud.common.core.jackson.databind.converter.CustomOffsetDateTimeDeserializer;
import com.lijiajia.cloud.common.core.jackson.databind.converter.CustomOffsetDateTimeSerializer;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;

/**
 * 自定义 mapper
 *
 * @author lijiajia
 * @since 2019-4-5
 */
public class CustomObjectMapper {
    public static ObjectMapper getInstance() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat(Constants.DEFAULT_DATE_TIME_PATTERN));
        mapper.setTimeZone(Constants.DEFAULT_TIME_ZONE);


        JavaTimeModule javaTimeModule = new JavaTimeModule();
        //序列化日期格式
        // LocalDateTime 2011-12-03T10:15:30 -> 2019-01-01 00:00:00
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(Constants.DEFAULT_DATE_TIME_FORMATTER));
        // OffsetDateTime 2011-12-03T10:15:30+01:00-> 2019-01-01 00:00:00
        javaTimeModule.addSerializer(OffsetDateTime.class, CustomOffsetDateTimeSerializer.INSTANCE);
        // javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(Constants.DEFAULT_DATE_FORMATTER));
        // javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(Constants.DEFAULT_TIME_FORMATTER));
        //反序列化日期格式
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(Constants.DEFAULT_DATE_TIME_FORMATTER));
        // OffsetDateTime 2011-12-03T10:15:30+01:00-> 2019-01-01 00:00:00
        javaTimeModule.addDeserializer(OffsetDateTime.class, CustomOffsetDateTimeDeserializer.INSTANCE);
        // javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(Constants.DEFAULT_DATE_FORMATTER));
        // javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(Constants.DEFAULT_TIME_FORMATTER));

        mapper.registerModule(javaTimeModule);

        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);

        return mapper;
    }
}
